/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package model;

import dao.ActivitiesDao;
import dao.FtpInfoCrud;
import dao.ActivityHistoryCrud;
import dao.ProviderDao;
import dao.ScheduleDataDao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import pojo.Activities;
import pojo.FtpInfo;
import pojo.ActivityHistory;
import pojo.Provider;
import pojo.Scheduledata;

/**
 *
 * @author Mostafa
 */
public class AddProvider {

    private String username;

    public AddProvider(String user) {
        this.username = user;
    }

    //create table for provider
    private void createTable(Connection c, Provider pro, FtpInfo fi, Scheduledata scdata, ActivityHistory log, String[] names, String[] types, Integer[] accuracylevels, boolean[] required) {
        try {
            LogFile.log(username, " began adding new provider his Name is : [" + pro.getName() + "] , and his Type is : " + pro.getType());
            String txt = "CREATE TABLE " + pro.getTableName() + "(";
            String headers = "";
            String insert = "insert into accuracy_levels ( al_id   ";
            String cols = "";
            String values = "";
            for (int i = 0; i < names.length; i++) {
                if (required[i]) {
                    txt += names[i] + " " + types[i] + " , ";
                    if (!(accuracylevels[i] == 0)) {
                        cols += " , " + names[i].toLowerCase() + "_by ";
                        values += " , " + accuracylevels[i];
                    }
                }
                headers += names[i] + " , ";
            }
            txt = txt.substring(0, txt.lastIndexOf(","));
            txt += "  ) ";
            cols += " ) ";
            LogFile.log(" System ", " executed that Query:[ " +txt+"] to create table for provider with Name :[ "+pro.getName()+"]");
            PreparedStatement ps = c.prepareStatement(txt);
            boolean rs = ps.execute();
            if (rs = true) {
                LogFile.log(" System ", "successfully created header table for provider [" + pro.getName() + "] with Name [" + pro.getTableName()+"]");
            } else if (rs == false) {
                LogFile.log(" System ", " failed to create header table for provider [" + pro.getName()+"]");
            }
            pro.setHeaders(headers);
            insertprovider(c,pro);
            
            Provider mypro = getProviderByName(c, pro.getName());
            values = " ( " + mypro.getPId().toString() + values + " ) ";
            insert += cols + " values " + values;

            scdata.setScId(mypro.getPId());
            addSchedule(c, scdata);
            
            fi.setFtpId(mypro.getPId());
            addFTPInfo(c, fi);

            Activities myact = getActivityByName(c,"add provider");
            log.setActivities(myact);
            log.setActivityName(myact.getName());
            log.setLiveServer(null);
            logAddOperation(c, log);

            PreparedStatement ps2 = c.prepareStatement(insert);
            boolean rs1=ps2.execute();
            if(rs1==true){
                LogFile.log(" System ", " successfully inserted accuracy levels for provider ["+pro.getName()+"] in Accuracy Levels Table in database");
            }
            else if(rs1==false){
                LogFile.log(" System ", " failed to insert accuracy levels for provider ["+pro.getName()+"] in accuracy levels table in database .");
            }
        } catch (SQLException ex) {
            Logger.getLogger(AddProvider.class.getName()).log(Level.SEVERE, null, ex);
            LogFile.log(" System ", " encountered the following exception while trying to define new provider with name ["+pro.getName()+"] , the problem is : ["+ex+"]");
        }
    }

    //Add New Provider Method
    public void addProvider(Connection c, Provider pro, FtpInfo fi, Scheduledata scdata, ActivityHistory log, String[] names, String[] types, Integer[] accuracylevels, boolean[] required) {
        createTable(c, pro, fi, scdata, log, names, types, accuracylevels, required);
        createScheduletask(c, scdata, pro.getName());
    }

    //create schedule task 
    public void createScheduletask(Connection c, Scheduledata scdata, String providerName) {
        if (OSDetector.isWindows() == true) {
            System.out.println("Hi Windows Server");
            new ScheduledTaskWindows(c).create(scdata, providerName);
        }
        if (OSDetector.isUnix() == true) {
            System.out.println("hi linux server");
            new ScheduledTaskLinux(c).create(scdata, providerName);
        }
    }
    
    //insert provider data in provider table
    public void insertprovider(Connection c,Provider pro){
        ProviderDao prDao = new ProviderDao(c);
        prDao.insert(pro);
    }
    
    //method to get provider data by his name
    public Provider getProviderByName(Connection c,String providerName){
        ProviderDao prDao = new ProviderDao(c);
        return prDao.getByName(providerName);
    }
    
    //add schedule data to its table
    public void addSchedule(Connection c ,Scheduledata scdata){
        ScheduleDataDao scDao = new ScheduleDataDao(c);
        scDao.add(scdata);
    }
    
    //add ftp information to its table
    public void addFTPInfo(Connection c,FtpInfo fi){
        FtpInfoCrud fc = new FtpInfoCrud(c);
        fc.add(fi);
    }
    
    //get Activity by Name
    public Activities getActivityByName(Connection c,String activityName){
        ActivitiesDao actdao = new ActivitiesDao(c);
        return actdao.getByName(activityName);
    }
    
    //log add new provider operation in database
    public void logAddOperation(Connection c ,ActivityHistory log){
        ActivityHistoryCrud logcrud = new ActivityHistoryCrud(c);
        logcrud.add(log);
    }
}
